import {
  _decorator,
  Component,
  Node,
  Prefab,
  UITransform,
  Vec3,
  instantiate,
  EventTouch,
} from 'cc';
import { EventBus, TYPE } from './Utils/EventBus';
import { GameManager } from './GameManager';
import PlantCardBase, { CardState } from './Card/PlantCardBase';
import { CommonData } from './Utils/CommonData';

const { ccclass, property } = _decorator;

@ccclass('GridLayer')
export class GridLayer extends Component {
  @property(Node)
  background: Node = null!;

  @property(Node)
  plantLayer: Node = null!;

  @property(Prefab)
  plantPrefab: Prefab = null!;

  @property(Prefab)
  car: Prefab[] = [];

  @property(Prefab)
  plant: Prefab = null!;

  @property(Prefab)
  cherrybombPrefab: Prefab = null!;

  @property(Prefab)
  gatlingpeaPrefab: Prefab = null!;

  @property(Prefab)
  chomperPerfab: Prefab = null!;

  @property(Prefab)
  repeaterPrefab: Prefab = null!;

  @property(Prefab)
  sunflowerPrefab: Prefab = null!;

  rows: number = 5;

  cols: number = 14;

  grid: (Node | null)[][] = [];

  private boundOnPlantDraggEnd:any;

  cellWidth: number = 0;
  cellHeight: number = 0;
  gridCenters: Vec3[][] = [];

  protected onLoad(): void {
    const uiTrans = this.node.getComponent(UITransform)!;
    const gridUI = this.node.getComponent(UITransform)!;

    this.cellWidth = gridUI.width / this.cols;

    this.cellHeight = gridUI.height / this.rows;

    for (let r = 0; r < this.rows; r++) {
      this.grid[r] = [];
      this.gridCenters[r] = [];
      for (let c = 0; c < this.cols; c++) {
        const x = -uiTrans.width / 2 + this.cellWidth * (c + 0.5);
        const y = uiTrans.height / 2 - this.cellHeight * (r + 0.5);
        this.grid[r][c] = null;
        this.gridCenters[r][c] = new Vec3(x, y, 0);
      }
      CommonData.instance.gridCenters = this.gridCenters;
    }

    this.node.on(Node.EventType.TOUCH_END, this.onTouchEnd, this);
    this.boundOnPlantDraggEnd = this.onPlantDraggEnd.bind(this)
    EventBus.on(TYPE.PLANT_DRAGG_END, this.boundOnPlantDraggEnd);
    this.car.forEach((carPrefab, index) => {
      const cart = instantiate(carPrefab);
      cart.setParent(this.node);
      const row = index;
      const col = 0;
      const pos = this.getPostionGrid(row, col);
      if (pos) cart.setPosition(pos);

      const uiTrans = cart.getComponent(UITransform);
      uiTrans.width = this.cellWidth * 0.8;
      uiTrans.height = this.cellHeight * 0.4;
      this.grid[row][col] = cart;
    });
  }

  protected onDestroy(): void {
    EventBus.off(TYPE.PLANT_DRAGG_END,this.boundOnPlantDraggEnd)
  }

  onPlantDraggEnd({
    localPos,
    node,
    sun,
    _this,
  }: {
    localPos: Vec3;
    node: Node;
    sun: number;
    _this: PlantCardBase;
  }) {
    console.log(this)
    const uiTrans = this.node.getComponent(UITransform)!;
    const col = Math.floor((localPos.x + uiTrans.width / 2) / this.cellWidth);
    const row = Math.floor((uiTrans.height / 2 - localPos.y) / this.cellHeight);
    if (col > 8) {
      console.log('植物必须种植在草地上');
      node.destroy();
      return;
    }
    if (!this.grid[row][col]) {
      const pos = this.getPostionGrid(row, col);
      node.setPosition(pos);
      this.grid[row][col] = node;
      GameManager._instance.sunCount -= sun;
      EventBus.emit(TYPE.PLANTING_SUCCESS);
      EventBus.emit(TYPE.SUN_CHANGE, GameManager._instance.sunCount);
      _this.setState(CardState.Cooing);
    } else {
      console.log('当前位置已经存在植物了');
      node.destroy();
    }
  }

  onTouchEnd(event: EventTouch) {
    const uiTrans = this.node.getComponent(UITransform)!;
    const touchPos = event.getUILocation();

    const localPos = uiTrans.convertToNodeSpaceAR(
      new Vec3(touchPos.x, touchPos.y, 0)
    );

    const col = Math.floor((localPos.x + uiTrans.width / 2) / this.cellWidth);
    const row = Math.floor((uiTrans.height / 2 - localPos.y) / this.cellHeight);

    if (col >= 0 && col < this.cols && row >= 0 && row < this.rows) {
      console.log(`点击了第 ${row} 行，第 ${col} 列`);
      if (!col) {
        console.log('点击了小推车');
      }
    } else {
      console.log('点到草坪外面了');
    }
  }

  getPostionGrid(row: number, col: number) {
    if (row < 0 || row >= this.rows || col < 0 || col >= this.cols) return null;
    return this.gridCenters[row][col];
  }
}
